import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { sequence, waybill } from 'jh-delvery-com';
import { Repository, getRepository } from 'typeorm';
import * as Moment from 'moment';

@Injectable()
export class AppService {
  constructor(
    @InjectRepository(waybill) private waybillRep: Repository<waybill>
  ) { }
  async getDataForLineName(date: string = Moment().format('YYYY-MM-DD'), centercode = 9900) {
    let a = await getRepository(waybill)
      .createQueryBuilder('waybill')
      // .select('lineCode as `路线编号` , lineName as `线路名称`,`status` as `不同状态`,COUNT(*) as `数量`')
      .select('lineCode, lineName ,`status`,COUNT(*) as count')
      .where(`createTime like :time`, { time: `%${date}%` })
      .andWhere(`centerCode = :center`, { center: centercode })
      .addGroupBy(`lineName,status`)
      .execute()
    return a
  }

  async getWaybillByTsNumber(date: string = Moment().format('YYYY-MM-DD'), centercode = 9900, tsNumber: string) {

    let a = await getRepository(waybill)
      .createQueryBuilder('waybill')
      // .select('lineCode as `路线编号` , lineName as `线路名称`,`status` as `不同状态`,COUNT(*) as `数量`')
      .select('lineCode, lineName ,`status`,loadingNumber,centerCode')
      .where(`createTime like :time`, { time: `%${date}%` })
      // .andWhere(`loadingNumber = :loadingNumber`,{loadingNumber:tsNumber})
      .andWhere(`centerCode = :center`, { center: centercode })
      // .andWhere(`status = :status`,{status:3})
      // .addGroupBy(`lineName,status`)
      .execute()
    return a
  }

  async getAllLineState(waybills) {
    if (waybills.length <= 0) return []
    let returnList = []
    
    for (let way of waybills) {
      let a = await getRepository(sequence)
        .createQueryBuilder('sequence')
        // .select('lineCode as `路线编号` , lineName as `线路名称`,`status` as `不同状态`,COUNT(*) as `数量`')
        .select('id,`index`,storeName, storeNumber ,`status`,unArrival,actualArrivalTime')
        .where(`loadingNumber = :loadingNumber`, { loadingNumber: way.loadingNumber })
        // .andWhere(`centerCode = :center`,{center:centercode})
        // .addGroupBy(`lineName,status`)
        .execute()
      returnList.push({
        centerCode:way.centerCode,
        status:way.status,
        lineName:way.lineName,
        lines:a
      })
      
    }
    
    return returnList
  }
}
